<template>
  <div class="chronic-disease-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="疾病名称">
          <el-input
            v-model="queryParams.diseaseName"
            placeholder="请输入疾病名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="ICD编码">
          <el-input
            v-model="queryParams.icdCode"
            placeholder="请输入ICD编码"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            v-permission="'disease:query'"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="button-group">
        <el-button
          type="primary"
          v-permission="'disease:add'"
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>新增慢性病
        </el-button>
      </div>
    </div>

    <!-- 慢性病表格 -->
    <el-table
      :data="diseaseList"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="diseaseName" label="疾病名称" width="180" />
      <el-table-column prop="icdCode" label="ICD编码" width="120" />
      <el-table-column prop="typeName" label="病种类型" width="150" />
      <el-table-column
        prop="description"
        label="疾病描述"
        width="200"
        show-overflow-tooltip
      />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button
            v-permission="'disease:edit'"
            size="small"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-permission="'disease:delete'"
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
          <el-button size="small" @click="handleDetail(row)"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
        ref="diseaseForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="疾病名称" prop="diseaseName">
          <el-input
            v-model="formData.diseaseName"
            placeholder="请输入疾病名称"
          />
        </el-form-item>
        <el-form-item label="病种类型" prop="typeId">
          <el-select
            v-model="formData.typeId"
            placeholder="请选择病种类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in diseaseTypeOptions"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="ICD编码" prop="icdCode">
          <el-input v-model="formData.icdCode" placeholder="请输入ICD编码" />
        </el-form-item>
        <el-form-item label="疾病描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入疾病描述"
          />
        </el-form-item>
        <el-form-item label="常见症状" prop="symptoms">
          <el-input
            v-model="formData.symptoms"
            type="textarea"
            :rows="3"
            placeholder="请输入常见症状"
          />
        </el-form-item>
        <el-form-item label="治疗方法" prop="treatment">
          <el-input
            v-model="formData.treatment"
            type="textarea"
            :rows="3"
            placeholder="请输入治疗方法"
          />
        </el-form-item>
        <el-form-item label="预防措施" prop="prevention">
          <el-input
            v-model="formData.prevention"
            type="textarea"
            :rows="3"
            placeholder="请输入预防措施"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <!-- 查看详情对话框 -->
  <el-dialog v-model="detailDialogVisible" title="慢性病详情" width="60%">
    <el-descriptions :column="1" border>
      <el-descriptions-item label="疾病名称">{{
        detailData.diseaseName
      }}</el-descriptions-item>
      <el-descriptions-item label="病种类型">{{
        detailData.typeName
      }}</el-descriptions-item>
      <el-descriptions-item label="ICD编码">{{
        detailData.icdCode
      }}</el-descriptions-item>
      <el-descriptions-item label="疾病描述">{{
        detailData.description
      }}</el-descriptions-item>
      <el-descriptions-item label="类型描述">{{
        detailData.typeDescription
      }}</el-descriptions-item>
      <el-descriptions-item label="常见症状">{{
        detailData.symptoms
      }}</el-descriptions-item>
      <el-descriptions-item label="治疗方法">{{
        detailData.treatment
      }}</el-descriptions-item>
      <el-descriptions-item label="预防措施">{{
        detailData.prevention
      }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDiseaseList,
  addDisease,
  updateDisease,
  deleteDisease,
  getTypeInfo
} from '@/api/chronicDisease'
import { getChronicDiseaseTypeList } from '@/api/chronicDiseaseType'

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  diseaseName: '',
  icdCode: ''
})

// 表格数据
const diseaseList = ref([])
const total = ref(0)
const loading = ref(false)
// 种类目录
const diseaseTypeOptions = ref([])
// 对话框控制
const detailDialogVisible = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)

// 表单数据
const formData = reactive({
  id: null,
  diseaseName: '',
  icdCode: '',
  description: '',
  symptoms: '',
  treatment: '',
  prevention: '',
  isDeleted: 0,
  typeId: null,
  typeName: ''
})
// 查看详情的数据
const detailData = reactive({
  diseaseName: '',
  icdCode: '',
  description: '',
  symptoms: '',
  treatment: '',
  prevention: '',
  typeName: '',
  typeDescription: ''
})

// 表单验证规则
const rules = reactive({
  diseaseName: [
    { required: true, message: '请输入疾病名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  icdCode: [{ max: 20, message: '长度不能超过20个字符', trigger: 'blur' }]
})
// 查看详情
const handleDetail = async (row) => {
  try {
    // 将 row 数据复制到 detailData
    Object.assign(detailData, row)
    // 获取病种类型信息
    const res = await getTypeInfo(row.id)
    detailData.typeName = res.data.data?.typeName || '未知类型'
    detailData.typeDescription = res.data.data?.description || '暂无描述'
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取病种信息失败')
    console.error(error)
  }
}
// 获取慢性病列表
const fetchDiseaseList = async () => {
  try {
    loading.value = true
    const res = await getDiseaseList(queryParams)
    const list = res.data.data.records || []

    // 批量获取 typeName 并合并到数据中
    const enrichedList = await Promise.all(
      list.map(async (item) => {
        try {
          const typeRes = await getTypeInfo(item.id)
          return {
            ...item,
            typeName: typeRes.data.data?.typeName || '未知类型'
          }
        } catch (error) {
          console.error(`获取病种信息失败：${item.id}`, error)
          return {
            ...item,
            typeName: '未知类型'
          }
        }
      })
    )
    diseaseList.value = enrichedList
    total.value = res.data.data.total
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.page = 1
  fetchDiseaseList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.diseaseName = ''
  queryParams.icdCode = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchDiseaseList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  fetchDiseaseList()
}

// 新增慢性病
const handleAdd = () => {
  dialogTitle.value = '新增慢性病'
  isAdd.value = true
  resetForm()
  dialogVisible.value = true
}

// 编辑慢性病
const handleEdit = async (row) => {
  dialogTitle.value = '编辑慢性病'
  isAdd.value = false

  // 先赋值基础信息
  Object.assign(formData, row)

  try {
    const res = await getTypeInfo(row.id)
    formData.typeId = res.data.data?.id || null
    formData.typeName = res.data.data?.typeName || ''
  } catch (error) {
    console.error('获取病种信息失败', error)
    formData.typeId = null
    formData.typeName = ''
  }

  dialogVisible.value = true
}

// 删除慢性病
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该慢性病记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(async () => {
      await deleteDisease(row.id)
      ElMessage.success('删除成功')
      fetchDiseaseList()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    diseaseName: '',
    icdCode: '',
    description: '',
    symptoms: '',
    treatment: '',
    prevention: '',
    isDeleted: 0,
    typeId: null,
    typeName: ''
  })
}

// 提交表单
const submitForm = async () => {
  try {
    if (isAdd.value) {
      await addDisease(formData)
      ElMessage.success('新增成功')
    } else {
      await updateDisease(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchDiseaseList()
  } catch (error) {
    console.error(error)
  }
}
// 获取病种类型列表
const queryParam = reactive({
  page: 1,
  pageSize: 10000
})
const fetchDiseaseTypeList = async () => {
  try {
    const res = await getChronicDiseaseTypeList(queryParam)
    diseaseTypeOptions.value = res.data.data.records || []
  } catch (error) {
    ElMessage.error('获取病种类型失败')
    console.error(error)
  }
}

// 初始化加载数据
onMounted(() => {
  // 获取慢性病列表
  fetchDiseaseList()
  // 获取慢性病种类列表
  fetchDiseaseTypeList()
})
</script>

<style scoped>
.chronic-disease-management {
  padding: 20px;
}

.operation-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.button-group {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-select {
  width: 100%;
}
</style>
